package com.bitejiuyeke.forum.services.impl;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.dao.ArticleReplyMapper;
import com.bitejiuyeke.forum.exception.ApplicationException;
import com.bitejiuyeke.forum.model.ArticleReply;
import com.bitejiuyeke.forum.services.IArticleReplyService;
import com.bitejiuyeke.forum.services.IArticleService;
import com.bitejiuyeke.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2024-02-08
 * Time: 16:20
 */
@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    ArticleReplyMapper articlereplyMapper;
    @Resource
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        //非空校验
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛异常
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
       //设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte)0);
        articleReply.setDeleteState((byte) 0);
        Date date = new  Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //插入数据
        int i = articlereplyMapper.insertSelective(articleReply);
        if (i != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw   new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新文章评论数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        //打印日志
        log.info("插入成功 article id"+articleReply.getArticleId() + " user id"+articleReply.getPostUserId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
       //非空校验
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //调用dao
        List<ArticleReply> articleReplies = articlereplyMapper.selectByArticleId(articleId);
        return  articleReplies;
    }
}
